﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using webnew.Common;
namespace webnew.UserControls
{
    public partial class Uc_FileDownLoad : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        ////////调用下载控件的例子,传入参数:下载文件对应表名和对应表ID
        ////////Uc_FileDownLoad1.UcShow("Sys_company", "1");  

        /// <summary>
        /// 显示下载控件
        /// </summary>
        /// <param name="tbName">下载文件对应表名</param>
        /// <param name="Id">对应表ID</param>
        public void UcShow(string tbName,string Id)
        {
            webnew.Common.CommonHelper.DataGrdBind(grdFileList, new BLL.Sys_Files().GetList(tbName,Id));

        }
        /// 附件下载
        /// </summary>
        /// <param name="strFullName">所要下载文件的物理路径</param>
        public void FileDownload(string strFullName)
        {

            FileInfo DownloadFile = new FileInfo(strFullName);
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Response.ContentType = "application/octet-stream"; 
            //转为UTF8码,支持中文字
            string DownFileName = HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8);
            //把"+"转为空格
            DownFileName = DownFileName.Replace("+", "%20");
            //转为旧文件名
            DownFileName = UploadFile.NewFileToOldFile(DownFileName);
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + DownFileName);
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            Response.End();
        }

        /// <summary>
        /// 文件下载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdFileList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //获取指定的文件路径
            string selValue = grdFileList.DataKeys[e.RowIndex]["FilePath"].ToString();
            //调用下载方法
            FileDownload(selValue);
        }

        /// <summary>
        /// 对文件列表进行处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdFileList_DataBound(object sender, EventArgs e)
        {
            //对读取出来的文件名进行处理
            foreach (GridViewRow gvRow in grdFileList.Rows)
            {
                gvRow.Cells[1].Text = UploadFile.NewFileToOldFile(gvRow.Cells[1].Text);
                gvRow.Cells[1].Text += " (" + (Convert.ToDouble(grdFileList.DataKeys[gvRow.RowIndex]["FileLength"])).ToString("F2") + "K)";
            }

        }

        
    }
}